package com.cloud.wms.ui.main.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.base.BaseListActivity;
import com.cloud.wms.ui.inside.replenish.LackQueryActivity;
import com.cloud.wms.ui.inside.replenish.ReplenishOrderActivity;
import com.cloud.wms.ui.main.contract.BaseInfoContract;
import com.cloud.wms.ui.main.entity.MemberEntity;
import com.cloud.wms.ui.main.entity.ModelEntity;
import com.cloud.wms.ui.main.entity.TaskMenuEntity;
import com.cloud.wms.ui.main.presnter.BaseInfoPresenter;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;
import com.google.android.material.button.MaterialButton;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * @Author:Chen
 * @Date: 2021-01-15 15:32
 * @Description:
 */
public class BaseMemberActivity extends BaseListActivity<MemberEntity, BaseInfoPresenter> implements BaseInfoContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.btn_next)
    MaterialButton btnNext;
    private int index = -1;
    private ArrayList<MemberEntity> memberList = new ArrayList<>();
    private long warehouseID;

    @Override
    protected int getResId() {
        return R.layout.activity_main_base;
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initBar() {
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tvTitle.setText("选择会员");
        btnNext.setText("进入");
        etSearch.setHint("查找会员");
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchMember(s);
            }
        });
        warehouseID = FineExApplication.component().loginCache().getWarehouseInfo().getWarehouseID();
        mPresenter.loadMemberList(warehouseID, true);
        List<ModelEntity> parentModelList = FineExApplication.component().loginCache().getParentModelList();
        if (parentModelList.size() > 1) {
            ArrayList<ModelEntity> childModelList = FineExApplication.component().loginCache().getModelList();
            List<String> parentModelNameList = new ArrayList<>();
            for (int i = 0; i < parentModelList.size(); i++) {
                parentModelNameList.add(parentModelList.get(i).getModuleName());
            }
            new AlertDialogBuilder(this)
                    .setCancelable(false)
                    .setTitle("选择操作版本类型")
                    .setPositiveButton(
                            "确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int checkedItemPosition =
                                            ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                                    if (checkedItemPosition != AdapterView.INVALID_POSITION) {
                                        //移除所选系统，子model集合中删除所有未选的model信息
                                        parentModelList.remove(checkedItemPosition);
                                        Iterator<ModelEntity> it = childModelList.iterator();
                                        for (int i = 0; i < parentModelList.size(); i++) {
                                            while (it.hasNext()) {
                                                ModelEntity childModelEntity = it.next();
                                                if (parentModelList.get(i).getModuleID() == childModelEntity.getParentModuleId())
                                                    it.remove();
                                            }
                                        }
                                        FineExApplication.component().loginCache().setModelList(childModelList);
                                    }
                                }
                            })
                    .setSingleChoiceItems(parentModelNameList.toArray((new CharSequence[parentModelNameList.size()])), 0, null)
                    .show();
        }
    }

    @SuppressLint("CheckResult")
    private void searchMember(Editable s) {
        index = -1;
        Observable.fromIterable(memberList)
                .filter(info -> TextUtils.isEmpty(s) || info.getMemberName().contains(s))
                .toList()
                .subscribe(data -> mAdapter.setNewInstance(data));
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_main_base;
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(this, 2);
    }

    @Override
    protected RecyclerView.ItemDecoration itemDecoration() {
        return GridItemDecoration.newBuilder().spanCount(2)
                .verticalDivider(null, DensityUtils.Dp2Px(this, 12), false)
                .horizontalDivider(null, DensityUtils.Dp2Px(this, 12), false)
                .build();
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, MemberEntity item) {
        helper.setText(R.id.tv_info_name, item.getMemberName());
        CheckedTextView checkView = (CheckedTextView) helper.getView(R.id.tv_info_name);
        checkView.setChecked(index == helper.getAdapterPosition());
        if (mAdapter.getData().size() == 1) {
            index = 0;
            checkView.setChecked(true);
        }
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<MemberEntity, BaseViewHolder> mAdapter, View view, int position) {
        super.itemClickListener(mAdapter, view, position);
        if (index == position) index = -1;
        else index = position;
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSuccess(Message message) {
        super.onSuccess(message);
        switch (message.what) {
            case BaseInfoPresenter.MEMBER:
                List<MemberEntity> list = (List<MemberEntity>) message.obj;
                memberList.clear();
                memberList.addAll(list);
                mAdapter.setNewInstance(list);

                MemberEntity memberInfo = FineExApplication.component().loginCache().getMemberInfo();
                if (memberInfo != null) {
                    for (int i = 0; i < list.size(); i++) {
                        MemberEntity memberEntity = list.get(i);
                        if (memberInfo.getMemberID() == memberEntity.getMemberID()) {
                            index = i;
                            scrollToPosition(rvList, index);
                            break;
                        }
                    }
                }
                break;
            case BaseInfoPresenter.TASK_MENU:
                MainActivity.start(this, ((ArrayList<TaskMenuEntity>) message.obj));
                this.finish();
                break;
        }
    }

    @Override
    protected boolean isRefresh() {
        return false;
    }

    @Override
    public void showEmpty() {
        mAdapter.setEmptyView(getEmptyDataView());
    }

    @Override
    public void showError() {
        mAdapter.setEmptyView(getErrorView());
    }

    protected View getEmptyDataView() {
        View notDataView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_empty, rvList, false);
        notDataView.setOnClickListener(v -> mPresenter.loadMemberList(warehouseID, true));
        return notDataView;
    }

    protected View getErrorView() {
        View errorView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_error, rvList, false);
        errorView.setOnClickListener(v -> mPresenter.loadMemberList(warehouseID, true));
        return errorView;
    }

    @OnClick({R.id.tv_pre, R.id.tv_jump, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_pre:
                BaseWarehouseActivity.start(this);
                this.finish();
                break;
            case R.id.tv_jump:
                mPresenter.loadMainTaskMenu();
                break;
            case R.id.btn_next:
                if (index >= 0) {
                    FineExApplication.component().loginCache().setMemberInfo(mAdapter.getData().get(index));
                    mPresenter.loadMainTaskMenu();
                } else
                    info("请选择会员");
                break;
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, BaseMemberActivity.class);
        context.startActivity(intent);
    }
}
